package com.pig4cloud.pig.iotData.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.iot.entity.IotDeviceMessageEntity;
import com.pig4cloud.pig.iot.service.IotDeviceMessageService;
import com.pig4cloud.pig.iotData.constant.IotDataKgnpkDevDataConstant;
import com.pig4cloud.pig.duorou.dto.DuorouKgnpkDevDataInfoDto;
import com.pig4cloud.pig.iotData.entity.AbnormalIndicator;
import com.pig4cloud.pig.iotData.entity.IotDataKgnpkDevDataEntity;
import com.pig4cloud.pig.iotData.entity.IotDataKgnpkDevDataInfoEntity;
import com.pig4cloud.pig.iotData.service.IotDataKgnpkDevDataInfoService;
import com.pig4cloud.pig.iotData.service.IotDataKgnpkDevDataService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * kg突然检测NPK实时存储的数据
 *
 * @author lty
 * @date 2024-11-18 22:37:28
 */
@Slf4j
@RestController
@RequiredArgsConstructor
//@PreAuthorize("@pms.hasPermission('iot_iotDevice_view')" ) todo 对于任何的设备数据查看 只要由iotdevice设备查看权限就好，不用单分权限 先不加
@RequestMapping("/duorouKgnpkDevData" )
@Tag(description = "duorouKgnpkDevData" , name = "kg突然检测NPK实时存储的数据管理" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class IotDataKgnpkDevDataController {

    private final IotDataKgnpkDevDataService iotDataKgnpkDevDataService;



	private final IotDataKgnpkDevDataInfoService iotDataKgnpkDevDataInfoService;

	@Resource
	private IotDeviceMessageService iotDeviceMessageService;
	/**
	 * 获取统计分析 最近一周的统计
	 */
	@Operation(summary = "统计数据_周" , description = "统计数据_周" )
	@GetMapping("/getDataAnalysisByWeek")
	public R getDataAnalysisByWeek(@ParameterObject  DuorouKgnpkDevDataInfoDto duorouKgnpkDevDataInfoDto) {

		// 获取当前时间和一周前的时间
		LocalDateTime now = LocalDateTime.now();
		// 获取最近七天 算上今天 的日期并将时间调整为 00:00
		LocalDateTime oneWeekAgo = now.minusDays(6).with(LocalTime.MIN);

		// 构造 LambdaQueryWrapper
		LambdaQueryWrapper<IotDataKgnpkDevDataEntity> lambdaQueryWrapper = Wrappers.lambdaQuery();
		lambdaQueryWrapper
				.eq(Objects.nonNull(duorouKgnpkDevDataInfoDto.getIotDeviceId()), IotDataKgnpkDevDataEntity::getIotDeviceId,duorouKgnpkDevDataInfoDto.getIotDeviceId())
				.apply("create_time IN (SELECT MAX(create_time) FROM iot_data_kgnpk_dev_data " +
						"WHERE create_time >= {0} GROUP BY DATE(create_time))", oneWeekAgo)
				.orderByAsc(IotDataKgnpkDevDataEntity::getCreateTime); // 按时间排序，方便验证

		// 执行查询 返回最近一周的数据 对于每一天的数据有多条的 取的是当天最新的哪一条
		List<IotDataKgnpkDevDataEntity> resultList = iotDataKgnpkDevDataService.list(lambdaQueryWrapper);
		// 打印结果
		System.out.println("打印最近一周的数据ID");
		resultList.forEach(System.out::println);

		List<DuorouKgnpkDevDataInfoDto> dataInfDtoListByDataIdAndMeasureName =new LinkedList<>();
		if(resultList.size()>0){
			List<Long> dataIdList = resultList.stream()
					.map(IotDataKgnpkDevDataEntity::getId) // 提取 ID
					.collect(Collectors.toList());// 收集为列表
			//根据获取到的dataId 从info中查询出这几条ID对应顺序再 info表里面存储的最终测量数据 指定只查询一种测量方法的数据
			dataInfDtoListByDataIdAndMeasureName=iotDataKgnpkDevDataService.getDataInfDtoListByDataIdAndMeasureName(dataIdList, duorouKgnpkDevDataInfoDto.getMeasureName());

//			打印这些ID对应的数据
			System.out.println("打印这些ID对应的数据详情");
			dataInfDtoListByDataIdAndMeasureName.forEach(System.out::println);
		}

		//处理数据 使得最后返回的是最近一周的数据 对于那一天没有数据的 以0填充
		List<DuorouKgnpkDevDataInfoDto> duorouKgnpkDevDataInfoDtos = processRecentSevenDaysData(dataInfDtoListByDataIdAndMeasureName);
		System.out.println("打印处理后的数据");
		duorouKgnpkDevDataInfoDtos.forEach(System.out::println);


		return R.ok(duorouKgnpkDevDataInfoDtos);
	}

	private List<DuorouKgnpkDevDataInfoDto> processRecentSevenDaysData (List<DuorouKgnpkDevDataInfoDto> dataInfDtoListByDataIdAndMeasureName) {

		// 获取今天和最近七天的日期
		LocalDate today = LocalDate.now();
		List<LocalDate> lastSevenDays = new ArrayList<>();
		for (int i = 6; i >= 0; i--) {
			lastSevenDays.add(today.minusDays(i));
		}

		// 定义格式化器
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

		// 按日期进行分组
		Map<LocalDate, DuorouKgnpkDevDataInfoDto> dataMap = dataInfDtoListByDataIdAndMeasureName.stream()
				.collect(Collectors.toMap(
						dto -> dto.getCreateTime().toLocalDate(), // 按日期分组
						dto -> dto,
						(existing, replacement) -> existing // 如果有重复，保留第一个
				));

		// 构造最终列表
		List<DuorouKgnpkDevDataInfoDto> result = new ArrayList<>();
		for (LocalDate date : lastSevenDays) {
			if (dataMap.containsKey(date)) {
				DuorouKgnpkDevDataInfoDto duorouKgnpkDevDataInfoDto = dataMap.get(date);
				duorouKgnpkDevDataInfoDto.setXdataDateStr(duorouKgnpkDevDataInfoDto.getCreateTime().format(formatter));
				// 如果该日期有数据，直接使用
				result.add(duorouKgnpkDevDataInfoDto); //dataMap.get(date)
			} else {
				// 如果没有数据，用默认值填充
				DuorouKgnpkDevDataInfoDto defaultDto = new DuorouKgnpkDevDataInfoDto();
				defaultDto.setCreateTime(date.atStartOfDay()); // 设置为当天的 00:00
				defaultDto.setMeasureValue(0.0);
				defaultDto.setXdataDateStr(date.atStartOfDay().format(formatter));
				result.add(defaultDto);
			}
		}

		return result;
	}




	/**
	 * 获取统计分析 最近一月的统计
	 */
	@Operation(summary = "统计数据_周" , description = "统计数据_周" )
	@GetMapping("/getDataAnalysisByMonth")
	public R getDataAnalysisByMonth(@ParameterObject  DuorouKgnpkDevDataInfoDto duorouKgnpkDevDataInfoDto) {

		// 获取当前时间
		LocalDateTime now = LocalDateTime.now();
		// 获取最近一年的开始时间，从去年的这个月开始
		LocalDateTime oneYearAgo = now.minusMonths(11).withDayOfMonth(1).with(LocalTime.MIN);

		// 构造 LambdaQueryWrapper
		LambdaQueryWrapper<IotDataKgnpkDevDataEntity> lambdaQueryWrapper = Wrappers.lambdaQuery();
		lambdaQueryWrapper
				.eq(Objects.nonNull(duorouKgnpkDevDataInfoDto.getIotDeviceId()),
						IotDataKgnpkDevDataEntity::getIotDeviceId, duorouKgnpkDevDataInfoDto.getIotDeviceId())
				.apply("create_time IN (" +
						"SELECT MAX(create_time) FROM iot_data_kgnpk_dev_data " +
						"WHERE create_time >= {0} " +
						"GROUP BY DATE_FORMAT(create_time, '%Y-%m')" + //DATE_FORMAT(create_time, '%Y-%m')  YEAR(create_time), MONTH(create_time)
						")", oneYearAgo)
				.orderByAsc(IotDataKgnpkDevDataEntity::getCreateTime); // 按时间排序，方便验证

		// 调用服务执行查询
		List<IotDataKgnpkDevDataEntity> resultList = iotDataKgnpkDevDataService.list(lambdaQueryWrapper);


		// 打印结果
		resultList.forEach(System.out::println);

		List<DuorouKgnpkDevDataInfoDto> dataInfDtoListByDataIdAndMeasureName=new LinkedList<>();
		if(resultList.size()>0){
			List<Long> dataIdList = resultList.stream()
					.map(IotDataKgnpkDevDataEntity::getId) // 提取 ID
					.collect(Collectors.toList());// 收集为列表
			//根据获取到的dataId 从info中查询出这几条ID对应顺序再 info表里面存储的最终测量数据 指定只查询一种测量方法的数据
			dataInfDtoListByDataIdAndMeasureName = iotDataKgnpkDevDataService.getDataInfDtoListByDataIdAndMeasureName(dataIdList, duorouKgnpkDevDataInfoDto.getMeasureName());

			dataInfDtoListByDataIdAndMeasureName.forEach(System.out::println);
		}


		//处理数据 使得最后返回的是最近一周的数据 对于那一天没有数据的 以0填充
		List<DuorouKgnpkDevDataInfoDto> duorouKgnpkDevDataInfoDtos = processRecentTwelveMonthData(dataInfDtoListByDataIdAndMeasureName);
		duorouKgnpkDevDataInfoDtos.forEach(System.out::println);


		return R.ok(duorouKgnpkDevDataInfoDtos);
	}
	private List<DuorouKgnpkDevDataInfoDto> processRecentTwelveMonthData (List<DuorouKgnpkDevDataInfoDto> dataInfDtoListByDataIdAndMeasureName) {

		// 获取当前日期
		LocalDate currentDate = LocalDate.now();
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");

		// 获取最近 12 个月的月份列表（包括当前月）
		List<String> lastTwelveMonths = new ArrayList<>();
		for (int i = 11; i >= 0; i--) {
			String month = currentDate.minusMonths(i).format(formatter);
			lastTwelveMonths.add(month);
		}

		// 按日期进行分组
		Map<String, DuorouKgnpkDevDataInfoDto> dataMap = dataInfDtoListByDataIdAndMeasureName.stream()
				.collect(Collectors.toMap(
						dto -> dto.getCreateTime().format(formatter), // 按日期分组
						dto -> dto,
						(existing, replacement) -> existing // 如果有重复，保留第一个
				));

		// 构造最终列表
		List<DuorouKgnpkDevDataInfoDto> result = new ArrayList<>();
		for (String date : lastTwelveMonths) {
			if (dataMap.containsKey(date)) {

				DuorouKgnpkDevDataInfoDto duorouKgnpkDevDataInfoDto = dataMap.get(date);
				duorouKgnpkDevDataInfoDto.setXdataDateStr(duorouKgnpkDevDataInfoDto.getCreateTime().format(formatter));
				// 如果该日期有数据，直接使用
				result.add(duorouKgnpkDevDataInfoDto); //dataMap.get(date)
			} else {
				// 如果没有数据，用默认值填充
				DuorouKgnpkDevDataInfoDto defaultDto = new DuorouKgnpkDevDataInfoDto();
				// 将字符串解析为 YearMonth
				YearMonth yearMonth = YearMonth.parse(date, formatter);
				// 转换为 LocalDate 并设置为当月的第一天
				LocalDateTime localDateTime = yearMonth.atDay(1).atStartOfDay();
				defaultDto.setCreateTime(localDateTime); // 设置为当天的 00:00
				defaultDto.setMeasureValue(0.0);
				defaultDto.setXdataDateStr(date);
				result.add(defaultDto);
			}
		}

		return result;
	}

	/**
     * 分页查询
     * @param page 分页对象
     * @param duorouKgnpkDevData kg突然检测NPK实时存储的数据
     * @return
     */
    @Operation(summary = "分页查询" , description = "分页查询" )
    @GetMapping("/page" )
    public R getDuorouKgnpkDevDataPage(@ParameterObject Page page, @ParameterObject IotDataKgnpkDevDataEntity duorouKgnpkDevData) {
        LambdaQueryWrapper<IotDataKgnpkDevDataEntity> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(Objects.nonNull(duorouKgnpkDevData.getIotDeviceId()), IotDataKgnpkDevDataEntity::getIotDeviceId,duorouKgnpkDevData.getIotDeviceId());
		wrapper.ge(Objects.nonNull(duorouKgnpkDevData.getCreateTime()), IotDataKgnpkDevDataEntity::getCreateTime,duorouKgnpkDevData.getCreateTime());
		wrapper.orderByDesc(IotDataKgnpkDevDataEntity::getCreateTime); //个面具时间讲学排序
        return R.ok(iotDataKgnpkDevDataService.page(page, wrapper));
    }


    /**
     * 通过id查询kg突然检测NPK实时存储的数据
     * @param id id
     * @return R
     */
    @Operation(summary = "通过id查询" , description = "通过id查询" )
    @GetMapping("/{id}" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(iotDataKgnpkDevDataService.getById(id));
    }



    /**
     * 修改kg突然检测NPK实时存储的数据
     * @param duorouKgnpkDevData kg突然检测NPK实时存储的数据
     * @return R
     */
    @Operation(summary = "修改kg突然检测NPK实时存储的数据" , description = "修改kg突然检测NPK实时存储的数据" )
    @SysLog("修改kg突然检测NPK实时存储的数据" )
    @PutMapping
    public R updateById(@RequestBody IotDataKgnpkDevDataEntity duorouKgnpkDevData) {
        return R.ok(iotDataKgnpkDevDataService.updateById(duorouKgnpkDevData));
    }

    /**
     * 通过id删除kg突然检测NPK实时存储的数据
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除kg突然检测NPK实时存储的数据" , description = "通过id删除kg突然检测NPK实时存储的数据" )
    @SysLog("通过id删除kg突然检测NPK实时存储的数据" )
    @DeleteMapping
    public R removeById(@RequestBody Long[] ids) {
        return R.ok(iotDataKgnpkDevDataService.removeBatchByIds(CollUtil.toList(ids)));
    }


    /**
     * 导出excel 表格
     * @param duorouKgnpkDevData 查询条件
   	 * @param ids 导出指定ID
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    public List<IotDataKgnpkDevDataEntity> export(IotDataKgnpkDevDataEntity duorouKgnpkDevData, Long[] ids) {
        return iotDataKgnpkDevDataService.list(Wrappers.lambdaQuery(duorouKgnpkDevData).in(ArrayUtil.isNotEmpty(ids), IotDataKgnpkDevDataEntity::getId, ids));
    }





	/**
	 * 新增kg突然检测NPK实时存储的数据 todo 这一个由kgbot完成需要
	 * @param dataList
	 * @return R
	 */
	@Operation(summary = "新增kg突然检测NPK实时存储的数据" , description = "新增kg突然检测NPK实时存储的数据" )
	@SysLog("新增kg突然检测NPK实时存储的数据" )
	@PostMapping(value = "/upload/data")
	public R uploadData(@RequestBody List<Long> dataList, @ParameterObject Long iotDeviceId) {
		IotDataKgnpkDevDataEntity duorouKgnpkDevData = new IotDataKgnpkDevDataEntity();
		duorouKgnpkDevData.setIotDeviceId(1859038055636193282L); // 默认设备ID

		if (Objects.nonNull(iotDeviceId)) {
			duorouKgnpkDevData.setIotDeviceId(iotDeviceId);
		}

		boolean save = iotDataKgnpkDevDataService.save(duorouKgnpkDevData);
		if (!save) {
			log.error("上传氮磷钾数据失败");
			return R.failed("上传氮磷钾数据失败");
		}

		// 处理并保存详细数据
		List<IotDataKgnpkDevDataInfoEntity> infoEntities = handleData(dataList, duorouKgnpkDevData.getId());
		boolean saveBatch = iotDataKgnpkDevDataInfoService.saveBatch(infoEntities);
		if (!saveBatch) {
			log.error("上传详细数据失败");
			return R.failed("上传详细数据失败");
		}

		iotDataKgnpkDevDataService.checkAllMeasures(duorouKgnpkDevData);
		return R.ok(null, "上传成功");
	}

	/**
	 * 处理返回的数据 严格按照要求
	 *
	 *  第一个元素是地址码 第二个是功能码 第三个转换为整数后的数据长度*2
	 *  第4 5 6 7 8 9 10分别对应土壤温度 土壤容积含水率 土壤电导率 土壤pH值 土壤含氮量 土壤含磷量 土壤含钾量
	 *  第11 12 13 14分别对应光照、空气温度、空气湿度、二氧化碳
	 *  最后一个是CRC校验，可不用
	 * @param dataList
	 */
	private List<IotDataKgnpkDevDataInfoEntity> handleData(List<Long> dataList, Long kgnpkDevDataId){
		Long devAddressCode = dataList.get(0); //todo 获取地址码 （可以作为iotDeviceId来使用，不过先不管它，后面再说吧）
		Long temperature = dataList.get(3); //土壤温度
		Long waterRate = dataList.get(4); //土壤容积含水率
		Long ecRate = dataList.get(5); //土壤电导率
		Long ph = dataList.get(6); //土壤pH值
		Long NData = dataList.get(7); //土壤含氮量
		Long PData = dataList.get(8); //土壤含磷量
		Long KData = dataList.get(9); //土壤含钾量
		Long illumination = dataList.get(10); // 光照
		Long airTemperature = dataList.get(11); // 空气温度
		Long airHumidity = dataList.get(12); // 空气湿度
		Long co2 = dataList.get(13); // 二氧化碳

		LinkedList<IotDataKgnpkDevDataInfoEntity> dataInfoEntityList = new LinkedList<>();
		IotDataKgnpkDevDataInfoEntity data1 = new IotDataKgnpkDevDataInfoEntity();
		data1.setKgnpkDevDataId(kgnpkDevDataId);
		data1.setMeasureName(IotDataKgnpkDevDataConstant.TU_RANG_WEN_DU.MEASURE_NAME);
		data1.setMeasureRawValue(temperature);
		data1.setMeasureValue(bigDecimalMultiply(temperature, IotDataKgnpkDevDataConstant.TU_RANG_WEN_DU.DATA_UNIT)); //上传的值是整数 对于小数也用整数保存了 要乘以数据单位即分辨率换算成小数
		data1.setMeasureUnit(IotDataKgnpkDevDataConstant.TU_RANG_WEN_DU.MEASURE_UNIT);
		data1.setDataUnit(IotDataKgnpkDevDataConstant.TU_RANG_WEN_DU.DATA_UNIT);
		data1.setMeasureRange(IotDataKgnpkDevDataConstant.TU_RANG_WEN_DU.MEASURE_RANGE);
		dataInfoEntityList.add(data1);


		IotDataKgnpkDevDataInfoEntity data2 = new IotDataKgnpkDevDataInfoEntity();
		data2.setKgnpkDevDataId(kgnpkDevDataId);
		data2.setMeasureName(IotDataKgnpkDevDataConstant.TU_RANG_WATER_RATE.MEASURE_NAME);
		data2.setMeasureRawValue(waterRate);
		data2.setMeasureValue(bigDecimalMultiply(waterRate, IotDataKgnpkDevDataConstant.TU_RANG_WATER_RATE.DATA_UNIT));
		data2.setMeasureUnit(IotDataKgnpkDevDataConstant.TU_RANG_WATER_RATE.MEASURE_UNIT);
		data2.setDataUnit(IotDataKgnpkDevDataConstant.TU_RANG_WATER_RATE.DATA_UNIT);
		data2.setMeasureRange(IotDataKgnpkDevDataConstant.TU_RANG_WATER_RATE.MEASURE_RANGE);
		dataInfoEntityList.add(data2);


		IotDataKgnpkDevDataInfoEntity data3 = new IotDataKgnpkDevDataInfoEntity();
		data3.setKgnpkDevDataId(kgnpkDevDataId);
		data3.setMeasureName(IotDataKgnpkDevDataConstant.TU_RANG_EC_RATE.MEASURE_NAME);
		data3.setMeasureRawValue(ecRate);
		data3.setMeasureValue(  bigDecimalMultiply(ecRate, IotDataKgnpkDevDataConstant.TU_RANG_EC_RATE.DATA_UNIT));
		data3.setMeasureUnit(IotDataKgnpkDevDataConstant.TU_RANG_EC_RATE.MEASURE_UNIT);
		data3.setDataUnit(IotDataKgnpkDevDataConstant.TU_RANG_EC_RATE.DATA_UNIT);
		data3.setMeasureRange(IotDataKgnpkDevDataConstant.TU_RANG_EC_RATE.MEASURE_RANGE);
		dataInfoEntityList.add(data3);


		IotDataKgnpkDevDataInfoEntity data4 = new IotDataKgnpkDevDataInfoEntity();
		data4.setKgnpkDevDataId(kgnpkDevDataId);
		data4.setMeasureName(IotDataKgnpkDevDataConstant.TU_RANG_PH.MEASURE_NAME);
		data4.setMeasureRawValue(ph);
		data4.setMeasureValue(bigDecimalMultiply(ph, IotDataKgnpkDevDataConstant.TU_RANG_PH.DATA_UNIT));
		data4.setMeasureUnit(IotDataKgnpkDevDataConstant.TU_RANG_PH.MEASURE_UNIT);
		data4.setDataUnit(IotDataKgnpkDevDataConstant.TU_RANG_PH.DATA_UNIT);
		data4.setMeasureRange(IotDataKgnpkDevDataConstant.TU_RANG_PH.MEASURE_RANGE);
		dataInfoEntityList.add(data4);



		IotDataKgnpkDevDataInfoEntity data5 = new IotDataKgnpkDevDataInfoEntity();
		data5.setKgnpkDevDataId(kgnpkDevDataId);
		data5.setMeasureName(IotDataKgnpkDevDataConstant.TU_RANG_N.MEASURE_NAME);
		data5.setMeasureRawValue(NData);
		data5.setMeasureValue(bigDecimalMultiply(NData, IotDataKgnpkDevDataConstant.TU_RANG_N.DATA_UNIT));
		data5.setMeasureUnit(IotDataKgnpkDevDataConstant.TU_RANG_N.MEASURE_UNIT);
		data5.setDataUnit(IotDataKgnpkDevDataConstant.TU_RANG_N.DATA_UNIT);
		data5.setMeasureRange(IotDataKgnpkDevDataConstant.TU_RANG_N.MEASURE_RANGE);
		dataInfoEntityList.add(data5);


		IotDataKgnpkDevDataInfoEntity data6 = new IotDataKgnpkDevDataInfoEntity();
		data6.setKgnpkDevDataId(kgnpkDevDataId);
		data6.setMeasureName(IotDataKgnpkDevDataConstant.TU_RANG_P.MEASURE_NAME);
		data6.setMeasureRawValue(PData);
		data6.setMeasureValue(bigDecimalMultiply(PData, IotDataKgnpkDevDataConstant.TU_RANG_P.DATA_UNIT) );
		data6.setMeasureUnit(IotDataKgnpkDevDataConstant.TU_RANG_P.MEASURE_UNIT);
		data6.setDataUnit(IotDataKgnpkDevDataConstant.TU_RANG_P.DATA_UNIT);
		data6.setMeasureRange(IotDataKgnpkDevDataConstant.TU_RANG_P.MEASURE_RANGE);
		dataInfoEntityList.add(data6);


		IotDataKgnpkDevDataInfoEntity data7 = new IotDataKgnpkDevDataInfoEntity();
		data7.setKgnpkDevDataId(kgnpkDevDataId);
		data7.setMeasureName(IotDataKgnpkDevDataConstant.TU_RANG_K.MEASURE_NAME);
		data7.setMeasureRawValue(KData);
		data7.setMeasureValue(bigDecimalMultiply(KData, IotDataKgnpkDevDataConstant.TU_RANG_K.DATA_UNIT));
		data7.setMeasureUnit(IotDataKgnpkDevDataConstant.TU_RANG_K.MEASURE_UNIT);
		data7.setDataUnit(IotDataKgnpkDevDataConstant.TU_RANG_K.DATA_UNIT);
		data7.setMeasureRange(IotDataKgnpkDevDataConstant.TU_RANG_K.MEASURE_RANGE);
		dataInfoEntityList.add(data7);


		// 光照数据处理
		IotDataKgnpkDevDataInfoEntity data8 = new IotDataKgnpkDevDataInfoEntity();
		data8.setKgnpkDevDataId(kgnpkDevDataId);
		data8.setMeasureName(IotDataKgnpkDevDataConstant.GUANG_ZHAO.MEASURE_NAME);
		data8.setMeasureRawValue(illumination);
		data8.setMeasureValue(bigDecimalMultiply(illumination, IotDataKgnpkDevDataConstant.GUANG_ZHAO.DATA_UNIT));
		data8.setMeasureUnit(IotDataKgnpkDevDataConstant.GUANG_ZHAO.MEASURE_UNIT);
		data8.setDataUnit(IotDataKgnpkDevDataConstant.GUANG_ZHAO.DATA_UNIT);
		data8.setMeasureRange(IotDataKgnpkDevDataConstant.GUANG_ZHAO.MEASURE_RANGE);
		dataInfoEntityList.add(data8);

		// 空气温度数据处理
		IotDataKgnpkDevDataInfoEntity data9 = new IotDataKgnpkDevDataInfoEntity();
		data9.setKgnpkDevDataId(kgnpkDevDataId);
		data9.setMeasureName(IotDataKgnpkDevDataConstant.KONG_QI_WEN_DU.MEASURE_NAME);
		data9.setMeasureRawValue(airTemperature);
		data9.setMeasureValue(bigDecimalMultiply(airTemperature, IotDataKgnpkDevDataConstant.KONG_QI_WEN_DU.DATA_UNIT));
		data9.setMeasureUnit(IotDataKgnpkDevDataConstant.KONG_QI_WEN_DU.MEASURE_UNIT);
		data9.setDataUnit(IotDataKgnpkDevDataConstant.KONG_QI_WEN_DU.DATA_UNIT);
		data9.setMeasureRange(IotDataKgnpkDevDataConstant.KONG_QI_WEN_DU.MEASURE_RANGE);
		dataInfoEntityList.add(data9);

		// 空气湿度数据处理
		IotDataKgnpkDevDataInfoEntity data10 = new IotDataKgnpkDevDataInfoEntity();
		data10.setKgnpkDevDataId(kgnpkDevDataId);
		data10.setMeasureName(IotDataKgnpkDevDataConstant.KONG_QI_SHI_DU.MEASURE_NAME);
		data10.setMeasureRawValue(airHumidity);
		data10.setMeasureValue(bigDecimalMultiply(airHumidity, IotDataKgnpkDevDataConstant.KONG_QI_SHI_DU.DATA_UNIT));
		data10.setMeasureUnit(IotDataKgnpkDevDataConstant.KONG_QI_SHI_DU.MEASURE_UNIT);
		data10.setDataUnit(IotDataKgnpkDevDataConstant.KONG_QI_SHI_DU.DATA_UNIT);
		data10.setMeasureRange(IotDataKgnpkDevDataConstant.KONG_QI_SHI_DU.MEASURE_RANGE);
		dataInfoEntityList.add(data10);

		// 二氧化碳数据处理
		IotDataKgnpkDevDataInfoEntity data11 = new IotDataKgnpkDevDataInfoEntity();
		data11.setKgnpkDevDataId(kgnpkDevDataId);
		data11.setMeasureName(IotDataKgnpkDevDataConstant.ER_YANG_HUA_TAN.MEASURE_NAME);
		data11.setMeasureRawValue(co2);
		data11.setMeasureValue(bigDecimalMultiply(co2, IotDataKgnpkDevDataConstant.ER_YANG_HUA_TAN.DATA_UNIT));
		data11.setMeasureUnit(IotDataKgnpkDevDataConstant.ER_YANG_HUA_TAN.MEASURE_UNIT);
		data11.setDataUnit(IotDataKgnpkDevDataConstant.ER_YANG_HUA_TAN.DATA_UNIT);
		data11.setMeasureRange(IotDataKgnpkDevDataConstant.ER_YANG_HUA_TAN.MEASURE_RANGE);
		dataInfoEntityList.add(data11);

		return dataInfoEntityList;

	}

	private Double bigDecimalMultiply(Long d1,Float d2){
		// 使用 BigDecimal 进行高精度计算
		BigDecimal temp = BigDecimal.valueOf(d1);
		BigDecimal unit = BigDecimal.valueOf(d2);
		BigDecimal result = temp.multiply(unit);

		// 保留两位小数并四舍五入
		BigDecimal roundedResult = result.setScale(2, RoundingMode.HALF_UP);

		return roundedResult.doubleValue();
	}

}